<?php


namespace app\admin\controller;


use app\BaseController;
use app\service\roominfoService;
use think\facade\Db;
use think\facade\View;

class ZftOrder extends Common
{
    //直付通账单
    public function index(){
        $com = $this->pidTokenId();
        //$whe['community_id'] = array('in',$com['community_id']);
        //$where[]=["community_id","in",$com["com_id"]];
        $where=array();
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);
        $data = request()->get();
        if (!empty($data)){
            if(!empty($data['community_name'])){
                $where[] = ["community_name","like","%".$data['community_name']."%"];
            }
            if(!empty($data['out_trade_no'])){
                $where[] = ["out_trade_no","like","%".$data['out_trade_no']."%"];
            }
            if(!empty($data['trade_no'])){
                $where[] = ["trade_no","like","%".$data['trade_no']."%"];
            }
            if(!empty($data['pay_money'])){
                $where[] = ["pay_money","like","%".$data['pay_money']."%"];
            }
            if(!empty($data["start_time"])&&(empty($data["end_time"]))){
                //$start_time=strtotime($data["start_time"])*1000;
                $start_time=$data["start_time"];
                $where[] = ['pay_time','>=',$start_time];
            }else if(empty($data["start_time"])&&(!empty($data["end_time"]))){
                $end_time=strtotime($data["end_time"])*1000;
                $end_time=$data["end_time"];
                $where[] = ['pay_time','<',$end_time];
            }else if(!empty($data["start_time"])&&(!empty($data["end_time"]))){
                //$start_time=strtotime($data["start_time"])*1000;
                //$end_time=strtotime($data["end_time"])*1000;
                $start_time=$data["start_time"];
                $end_time=$data["end_time"];
                $where[] = ['pay_time','>=',$start_time];
                $where[] = ['pay_time','<',$end_time];
            }

            View::assign('where',$where);
            $where = array_filter($where);
            if(array_key_exists('settle_status', $data)&&$data['settle_status']!=''){
                $where[] = ["settle_status","=",$data['settle_status']];
            }
        }
        //var_dump($where);

        $page = request()->has('page') ? request()->get('page') : 1;

        $export = $where;

        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $list=Db::name('zft_order_success')
            ->where($where)
            ->order('uid','desc')
            ->paginate([
                'list_rows'=> 20,
                'page'  =>  $page,
                'query' =>  $data
            ]);
        //var_dump($list);
        $number=Db::name('zft_order_success')->where($where)->count();
        $money=0;
        //$money=Db::name('zft_order_success')->where($where)->sum("pay_money");
        View::assign("number",$number);
        View::assign("list",$list);
        View::assign("money",$money);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch("index");
    }

    //导出账单数据
//    public function orderExport(){
//        //获取账单数据
//        $id = request()->param('id');
//        $export = request()->param('export');
//        //Log::write(request()->param(),"账单导出参数");
//        $export = str_replace("|","\"",$export);
//        if(!empty($id)){
//            $id = explode(',',request()->param('id'));
//            $billList = (new billService())->billEntryIdInfo($id);
//            if (count($billList) != count($id)) {
//                return json(['error' => '账单信息不完整']);
//            }
//        }else{
//            //查询小区信息
//            $com = $this->pidTokenId();
//            $community_id = $com['community_id'];
//            $where = json_decode($export,true);
//            $gmtstart = $where['gmtstart'];
//            $gmtend = $where['gmtend'];
//            unset($where['gmtstart']);
//            unset($where['gmtend']);
//            $billList = (new billService())->billWhereExport($community_id,$where,$gmtstart,$gmtend);
//            if(empty($billList)){
//                return json(['error' => '没有账单数据']);
//            }
//        }
//        //var_dump($billList);die;
//        //设置表头
//        //引入PHPExcel类
//        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
//        $objPHPExcel = new \PHPExcel();
//        //设置表头
//        $objPHPExcel->setActiveSheetIndex(0)
//            ->setCellValue('A1', '支付宝账单编号')
//            ->setCellValue('B1', '小区名称')
//            ->setCellValue('C1', '完整门牌号')
//            ->setCellValue('D1', '业主姓名')
//            ->setCellValue('E1', '业主电话')
//            ->setCellValue('F1', '费用类型')
//            ->setCellValue('G1', '账期')
//            ->setCellValue('H1', '出账日期')
//            ->setCellValue('I1', '截止日期')
//            ->setCellValue('J1', '账单金额')
//            ->setCellValue('K1', '折扣金额')
//            ->setCellValue('L1', '付款状态')
//            ->setCellValue('M1', '付款类型')
//            ->setCellValue('N1', '付款时间')
//            ->setCellValue('O1', '票据号')
//            ->setCellValue('P1', '账单备注');
//
//        $i=2;  //定义一个i变量，目的是在循环输出数据是控制行数
//        $count = count($billList);  //计算有多少条数据
//        for ($i = 2; $i <= $count+1; $i++) {
//            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $billList[$i-2]["bill_entry_id"]);
//            //根据小区ID查询小区名称
//            $commId = $billList[$i-2]["community_id"];
//            $communityName = (new roominfoService())->communityIdName($commId);
//            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $communityName['community_name']);
//            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $billList[$i-2]["room_address"]);
//            //根据完整门牌号查询业主信息
//            $address = $billList[$i-2]["room_address"];
//            $owner = (new billService())->roomId($commId,$address);
//            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $owner['owner_name']);
//            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $owner['owner_phone']);
//            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $billList[$i-2]["cost_type"]);
//            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $billList[$i-2]["acct_period"]);
//            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $billList[$i-2]["release_day"]);
//            $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $billList[$i-2]["deadline"]);
//            $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $billList[$i-2]["bill_entry_amount"]);
//            $discount_money="";
//            if(!empty($billList[$i-2]["discount_money"]))
//            {
//                $discount_money_arr=explode("(",$billList[$i-2]["discount_money"]);
//                $discount_money=$discount_money_arr[0];
//            }
//            $objPHPExcel->getActiveSheet()->setCellValue('K' . $i,$discount_money);
//
//            //判断账单状态
//            if($billList[$i-2]["status"] == 'TRADE_SUCCESS'){
//                $status = '已付款';
//            }elseif($billList[$i-2]["status"] == 'UNDER_PAYMENT'){
//                $status = '待支付';
//            }elseif($billList[$i-2]["status"] == 'WAIT_PAYMENT'){
//                $status = '待缴费';
//            }elseif($billList[$i-2]["status"] == 'OUT_OF_DATE'){
//                $status = '已逾期';
//            }
//            $objPHPExcel->getActiveSheet()->setCellValue('L' . $i, $status);
//            $objPHPExcel->getActiveSheet()->setCellValue('M' . $i, $billList[$i-2]["pay_type"]);
//            $objPHPExcel->getActiveSheet()->setCellValue('N' . $i, $billList[$i-2]["gmt_payment"]);
//            $objPHPExcel->getActiveSheet()->setCellValue('O' . $i, $billList[$i-2]["ticket"]);
//            $objPHPExcel->getActiveSheet()->setCellValue('P' . $i, $billList[$i-2]["remarks"]);
//        }
//        $objPHPExcel->getActiveSheet()->setTitle('账单信息');      //设置sheet的名称
//        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
//        header('Content-Disposition: attachment;filename="账单信息.xls"');
//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007"); //通过PHPExcel_IOFactory的写函数将上面数据写出来
//        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
//    }
    public function doSettle(){
        $id=request()->get("id");
        $info=Db::name('zft_order_success')->where("uid",$id)->find();
        if(empty($info)){
            return "账单不存在";
        }
        if($info["settle_status"]=="1"){
            return "账单已结算";
        }
         $jobQueueName  	  = "app\job\ZftSettleConfirmOrder";
         $jobData       	  = [ 'id' =>$id ] ;
         $res= \think\facade\Queue::push($jobQueueName,$jobData);

        $queueName  	  = "app\job\ZftNotifyUrl";
        $jobData       	  = [ 'id' =>$info["id"] ,"order_uid"=>$info["uid"],"alipay_notify_con"=>$info["alipay_notify_con"],"community_id"=>$info["community_id"]] ;
        $resu= \think\facade\Queue::push($queueName,$jobData);
        return "结算任务已下发";
    }
    //直付通结算账单
    public function settle(){
        //var_dump(env("APP.royalty_trans_in"));
        $com = $this->pidTokenId();
        //$whe['community_id'] = array('in',$com['community_id']);
        $where=array();
        //$where[]=["community_id","in",$com["com_id"]];
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);

        $data = request()->get();
        //var_dump($data);
        if (!empty($data)){
            if(!empty($data['community_name'])){
                $where[] = ["community_name","like","%".$data['community_name']."%"];
            }
            if(!empty($data["start_time"])&&(empty($data["end_time"]))){
                //$start_time=strtotime($data["start_time"])*1000;
                $start_time=$data["start_time"];
                $where[] = ['ctime','>=',$start_time];
            }else if(empty($data["start_time"])&&(!empty($data["end_time"]))){
                $end_time=strtotime($data["end_time"])*1000;
                $end_time=$data["end_time"];
                $where[] = ['ctime','<=',$end_time];
            }else if(!empty($data["start_time"])&&(!empty($data["end_time"]))){
                //$start_time=strtotime($data["start_time"])*1000;
                //$end_time=strtotime($data["end_time"])*1000;
                $start_time=$data["start_time"];
                $end_time=$data["end_time"];
                $where[] = ['ctime','>=',$start_time];
                $where[] = ['ctime','<=',$end_time];
            }

            View::assign('where',$where);
            $where = array_filter($where);


        }
        //var_dump($where);

        $page = request()->has('page') ? request()->get('page') : 1;

        $export = $where;

        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $list=Db::name('zft_settle_order')
            ->where($where)
            ->order('id','desc')
            ->paginate([
                'list_rows'=> 10,
                'page'  =>  $page,
                'query' =>  $data
            ]);
        //var_dump($list);
        $number=Db::name('zft_settle_order')->where($where)->count();
        View::assign("number",$number);
        if($number>0){

        }
        $order_money=Db::name('zft_settle_order')->where($where)->sum('order_money');
        $settle_money=Db::name('zft_settle_order')->where($where)->sum('settle_money');
        View::assign("order_money",$order_money);
        View::assign("settle_money",$settle_money);
        View::assign("list",$list);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch("settle");
    }

    public function statistics(){
        $com = $this->pidTokenId();
        //$whe['community_id'] = array('in',$com['community_id']);
        $where[]=["community_id","in",$com["com_id"]];
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);

        $data = request()->get();
        //var_dump($data);
        if (!empty($data)){
            if(!empty($data['community_name'])){
                $where[] = ["community_name","like","%".$data['community_name']."%"];
            }
            if(!empty($data["start_time"])&&(empty($data["end_time"]))){
                //$start_time=strtotime($data["start_time"])*1000;
                $start_time=$data["start_time"];
                $where[] = ['pay_time','>=',$start_time];
            }else if(empty($data["start_time"])&&(!empty($data["end_time"]))){
                $end_time=strtotime($data["end_time"])*1000;
                $end_time=$data["end_time"];
                $where[] = ['pay_time','<=',$end_time];
            }else if(!empty($data["start_time"])&&(!empty($data["end_time"]))){
                //$start_time=strtotime($data["start_time"])*1000;
                //$end_time=strtotime($data["end_time"])*1000;
                $start_time=$data["start_time"];
                $end_time=$data["end_time"];
                $where[] = ['pay_time','>=',$start_time];
                $where[] = ['pay_time','<=',$end_time];
            }

            View::assign('where',$where);
            $where = array_filter($where);


        }
        //var_dump($where);

        $page = request()->has('page') ? request()->get('page') : 1;

        $export = $where;

        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $list=Db::name('zft_statistics_day')
            ->where($where)
            ->order('id','desc')
            ->paginate([
                'list_rows'=> 10,
                'page'  =>  $page,
                'query' =>  $where
            ]);
        //var_dump($list);
        $number=Db::name('zft_statistics_day')->where($where)->count();
        View::assign("number",$number);

        View::assign("list",$list);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        return View::fetch("statistics");
    }
    public function logInfo(){
        $id=request()->get("id");
        $info=Db::name('zft_log_settle_confirm')->where("order_uid",$id)->select();

    }

    public function refund(){
        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            $user=Db::table('zft_black_user')->where("user_id",$data["user_id"])->find();
            if(!empty($user)){
                return "改用户已经添加";
            }
            $data["create_time"]=date("Y-m-d H:i:s");
            //将数据插入数据库
            $result = Db::name('zft_black_user')->insert($data);
            //判断数据是否插入成功
            if($result){
                $this->success('添加成功',url('index'));
            }else{
                $this->error('添加失败',url('add'));
            }
        }else{
            return View::fetch('refund');
        }
    }

}